package com.siyoumi.app.modules.app_ess.service;

import com.siyoumi.app.entity.EssClass;
import com.siyoumi.app.entity.EssClassUser;
import com.siyoumi.app.entity.EssUser;
import com.siyoumi.app.modules.app_ess.vo.VoEssAddStudent;
import com.siyoumi.app.modules.app_ess.vo.VoEssCancelClass;
import com.siyoumi.app.modules.app_ess.vo.VaEssClass;
import com.siyoumi.app.service.EssClassService;
import com.siyoumi.app.service.EssClassUserService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.service.IWebService;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

//班级
@Slf4j
@Service
public class SvcEssClass
        implements IWebService {
    static public SvcEssClass getBean() {
        return XSpringContext.getBean(SvcEssClass.class);
    }

    static public EssClassService getApp() {
        return EssClassService.getBean();
    }


    public EssClassUser getEntityClassUser(String uid) {
        JoinWrapperPlus<EssClassUser> query = listUserQuery();
        query.eq("ecu_uid", uid);

        return EssClassUserService.getBean().first(query);
    }

    public List<Map<String, Object>> getList() {
        return getList(null);
    }

    public List<Map<String, Object>> getList(String uid) {
        JoinWrapperPlus<EssClass> query = listQuery();
        query.select("eclass_id", "eclass_name");

        if (XStr.hasAnyText(uid)) { //查询某学生班级信息
            String sqlExists = "SELECT 1 FROM wx_app_x.t_ess_class_user WHERE ecu_uid = {0} AND ecu_class_id = eclass_id";
            query.exists(sqlExists, uid);
        }

        return getApp().getMaps(query);
    }

    /**
     * 根据uid获取班级列表
     *
     * @param uid
     */
    public List<String> getClassIds(String uid) {
        JoinWrapperPlus<EssClassUser> query = listUserQuery();
        query.eq("ecu_uid", uid);
        query.select("ecu_class_id");
        List<Map<String, Object>> list = EssClassUserService.getBean().getMaps(query);

        return list.stream().map(item -> (String) item.get("ecu_class_id")).collect(Collectors.toList())
                .stream().distinct().collect(Collectors.toList());
    }

    public JoinWrapperPlus<EssClass> listQuery() {
        return listQuery(InputData.getIns());
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<EssClass> listQuery(InputData inputData) {
        String name = inputData.input("name");

        JoinWrapperPlus<EssClass> query = getApp().join();
        query.eq("eclass_x_id", XHttpContext.getX())
                .eq("eclass_del", 0);
        query.orderByAsc("eclass_order")
                .orderByDesc("id");
        if (XStr.hasAnyText(name)) { //名称
            query.like("eclass_name", name);
        }

        return query;
    }

    public JoinWrapperPlus<EssClassUser> listUserQuery() {
        return listUserQuery(InputData.getIns());
    }

    public JoinWrapperPlus<EssClassUser> listUserQuery(String classId) {
        InputData inputData = InputData.getIns();
        inputData.put("class_id", classId);
        return listUserQuery(inputData);
    }

    public JoinWrapperPlus<EssClassUser> listUserQuery(InputData inputData) {
        String classId = inputData.input("class_id");

        JoinWrapperPlus<EssClassUser> query = EssClassUserService.getBean().join();
        query.eq("ecu_x_id", XHttpContext.getX());

        if (XStr.hasAnyText(classId)) {
            query.eq("ecu_class_id", classId);
        }

        return query;
    }

    /**
     * 更新人数
     *
     * @param classId
     * @param type
     */
    public void updateTotal(String classId, Integer type) {
        JoinWrapperPlus<EssClassUser> query = listUserQuery(classId);
        query.eq("ecu_user_type", type);
        Long count = EssClassUserService.getBean().count(query);

        EssClass entity = new EssClass();
        entity.setEclass_id(classId);
        if (type == 1) { //老师
            entity.setEclass_teacher_total(count);
        } else { //学生
            entity.setEclass_student_total(count);
        }
        getApp().updateById(entity);
    }

    /**
     * 获取uid
     *
     * @param classId
     * @param type
     */
    public List<String> getUids(String classId, Integer type) {
        JoinWrapperPlus<EssClassUser> query = listUserQuery(classId);
        query.eq("ecu_user_type", type);
        query.select("ecu_uid");
        List<Map<String, Object>> list = EssClassUserService.getBean().getMaps(query);
        return list.stream().map(item -> (String) item.get("ecu_uid")).collect(Collectors.toList());
    }

    /**
     * 删除老师关系
     *
     * @param classId
     */
    public XReturn delClassTeacher(String classId) {
        JoinWrapperPlus<EssClassUser> query = listUserQuery(classId);
        query.eq("ecu_user_type", 1);
        List<EssClassUser> list = EssClassUserService.getBean().get(query);
        if (!list.isEmpty()) {
            List<String> ids = list.stream().map(item -> item.getKey()).collect(Collectors.toList());
            EssClassUserService.getBean().delete(ids);

            for (EssClassUser entityUser : list) {
                EssClassUser entityClassUser = getEntityClassUser(entityUser.getEcu_uid());
                if (entityClassUser != null) { //老师存在分班
                    continue;
                }
                SvcEssUser.getBean().updateSetClass(entityUser.getEcu_uid(), 0);
            }
        }
        return EnumSys.OK.getR();
    }

    public XReturn edit(InputData inputData, VaEssClass vo) {
        List<String> ignoreField = new ArrayList<>();
        if (inputData.isAdminEdit()) {
            ignoreField.add("eclass_acc_id");
        }

        return XApp.getTransaction().execute(status -> {
            XReturn r = getApp().saveEntity(inputData, vo, true, ignoreField);
            EssClass entity = r.getData("entity");
            if (vo.getTeacher_set() == 1) {
                //删除关系
                delClassTeacher(entity.getKey());
                //添加老师
                List<EssClassUser> list = new ArrayList<>();
                for (String uid : vo.getTeacher_uids()) {
                    EssClassUser entityUser = newClassUser(entity.getKey(), 1, uid);
                    list.add(entityUser);

                    SvcEssUser.getBean().updateSetClass(entityUser.getEcu_uid(), 1);
                }
                EssClassUserService.getBean().saveBatch(list);
                //更新总数
                updateTotal(entity.getKey(), 1);
            }

            return r;
        });
    }

    public EssClassUser newClassUser(String classId, Integer type, String uid) {
        EssClassUser entityUser = new EssClassUser();
        entityUser.setEcu_x_id(XHttpContext.getX());
        entityUser.setEcu_class_id(classId);
        entityUser.setEcu_user_type(type);
        entityUser.setEcu_uid(uid);
        entityUser.setAutoID();

        return entityUser;
    }

    /**
     * 删除
     */
    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        XReturn r = XReturn.getR(0);

        //判断是否存在学生
        getApp().delete(ids);

        return r;
    }

    /**
     * 学生分班
     *
     * @param vo
     */
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public XReturn studentAddClass(VoEssAddStudent vo) {
        List<EssClassUser> list = new ArrayList<>();
        for (String uid : vo.getUids()) {
            EssClassUser entity = newClassUser(vo.getClass_id(), 0, uid);
            list.add(entity);

            SvcEssUser.getBean().updateSetClass(uid, 1);
        }
        EssClassUserService.getBean().saveBatch(list);
        //更新总数
        updateTotal(vo.getClass_id(), 0);

        return EnumSys.OK.getR();
    }


    /**
     * 学生取消分班
     *
     * @param vo
     */
    @Transactional(rollbackFor = Exception.class)
    public XReturn studentCancelClass(VoEssCancelClass vo) {
        String classId = null;

        List<EssUser> listUser = SvcEssUser.getApp().get(vo.getIds());
        for (EssUser entity : listUser) {
            if (Objects.equals(entity.getEuser_type(), 1)) {
                //老师，不能取消，到老师编辑页操作
                continue;
            }

            EssClassUser entityClassUser = SvcEssClass.getBean().getEntityClassUser(entity.getKey());
            if (entityClassUser != null) { //删除关系
                EssClassUserService.getBean().delete(entityClassUser.getKey());
                SvcEssUser.getBean().updateSetClass(entity.getKey(), 0);

                classId = entityClassUser.getEcu_class_id();
            }
        }

        if (XStr.hasAnyText(classId)) { //更新总数
            SvcEssClass.getBean().updateTotal(classId, 0);
        }

        return EnumSys.OK.getR();
    }
}
